<template>
    <el-row style="height: 670px;width: 100%;" :gutter="4" ref="allBox">
        <el-col :span="4" ref="materielTypeBox" class="left-sider">
            <div style="margin-left: 20px;margin-top: 10px;height: 95%;box-shadow: 0 0 8px 0 rgba(232,237,250,.6),0 2px 4px 0 rgba(232,237,250,.5);">
                <div class="operatBtnWrapper" style="color: #ef8200;text-align: center;font-size: 20px;">类别列表</div>
                <el-tree :data="typeData" :props="defaultProps" node-key="id" empty-text="没有数据" highlight-current :expand-on-click-node="false" @node-click="nodeClick">
                    <span class="custom-tree-node" slot-scope="{ node, data }" style="height: 100%;line-height: 100%;">
                        <span @click.stop="nodeClick(node.data)" style="padding: 7px 0;">{{ node.label }}</span>
                    </span>
                </el-tree>
            </div>
        </el-col>
        <el-col :span="20" ref="materielBox" class="right-content">
            <el-col style="width: 830px;margin: 0 auto;margin-left: 10px;margin-top: 10px;padding-bottom: 60px;">
                <div style="width: 820px;padding-bottom: 60px;box-shadow: 0 0 8px 0 rgba(232,237,250,.6),0 2px 4px 0 rgba(232,237,250,.5)">
                    <div style="width: 100%;text-align: center;font-size: 30px;height: 80px;line-height: 80px;color: #ef8200;">{{this.formTitle}}</div>
                    <span>
                        <el-form :label-position="right" :rules="rules" label-width="100px" :model="materielForm" ref="materielForm" action="">
                            <el-row style="width: 100%">
                                    <el-col style="width: 50%">
                                        <el-form-item label="产品类别" prop="typeId">
                                            <el-cascader
                                                    expand-trigger="hover"
                                                    clearable
                                                    :options="typeData"
                                                    v-model="materielForm.typeId"
                                                    placeholder="产品类别"
                                                    @change="handleChange" style="width: 250px;">
                                            </el-cascader>
                                        </el-form-item>
                                        <el-form-item label="产品名称" prop="materielName">
                                            <el-input v-model.trim="materielForm.materielName" class="inputTxtWrapper" placeholder="产品名称" style="width: 200px;"></el-input>
                                        </el-form-item>
                                        <el-form-item label="编号" prop="no">
                                            <el-input v-model.trim="materielForm.no" class="inputTxtWrapper"  placeholder="编号" style="width: 200px;"></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col style="width: 50%">
                                        <el-form-item label="规格型号" prop="spec">
                                            <el-input v-model.trim="materielForm.spec" class="inputTxtWrapper"  placeholder="规格型号" style="width: 200px;"></el-input>
                                        </el-form-item>
                                        <el-form-item label="使用状态" prop="state">
                                            <el-select v-model="materielForm.state" placeholder="使用状态,默认常用" style="width: 250px;">
                                                <el-option  style="width: 250px;" label="常用" value="0"></el-option>
                                                <el-option label="样品" value="1"></el-option>
                                                <el-option label="禁用" value="2"></el-option>
                                            </el-select>
                                        </el-form-item>
                                        <el-form-item label="单价" prop="price">
                                            <el-input v-model.number="materielForm.price" class="inputTxtWrapper"  placeholder="单价: 整数或两位小数" style="width: 200px;"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-form-item v-for="item in this.addField" :label="item.show_name" :key="item.id">
                                    <el-input v-model.trim="addFieldForm[item.field_name]" :placeholder="item.show_name" class="inputTxtWrapper" style="width: 660px;"></el-input>
                                </el-form-item>
                                <el-form-item label="备注" prop="remarks">
                                    <el-input v-model.trim="materielForm.remarks" class="inputTxtWrapper"  placeholder="备注" style="width: 660px;"></el-input>
                                </el-form-item>
                                <el-row style="width: 100%">
                                    <el-col style="width: 50%">
                                        <el-form-item label="图片" prop="images">
                                            <el-upload
                                                    action=""
                                                    list-type="picture"
                                                    class="upload-demo"
                                                    ref="imageUpload"
                                                    :on-preview="handlePictureCardPreview"
                                                    multiple
                                                    show-file-list
                                                    :file-list="imageList"
                                                    :accept="allowImage.type"
                                                    limit="5"
                                                    name="image"
                                                    :auto-upload="false"
                                                    :before-upload="beforeUploadImage"
                                                    :on-exceed="exceed"
                                                    :on-change="onImageChange"
                                                    :on-remove="onImageRemove">
                                                <el-button size="small" type="primary">点击添加</el-button>
                                                <div slot="tip" class="el-upload__tip">最多只能上传5张图片，每张大小不能超过500kb</div>
                                            </el-upload>
                                        </el-form-item>
                                    </el-col>
                                    <el-col style="width: 50%">
                                        <el-form-item label="资料" prop="files">
                                            <el-upload
                                                    action=""
                                                    class="upload-demo"
                                                    ref="fileUpload"
                                                    :on-change="onFileChange"
                                                    limit="1"
                                                    :file-list="fileList"
                                                    name="file"
                                                    :auto-upload="false"
                                                    :before-upload="beforeUploadFile"
                                                    :on-remove="onFileRemove">
                                                <el-button size="small" type="primary">点击添加</el-button>
                                                <div slot="tip" class="el-upload__tip">只能上传一个文件，大小不超过2M</div>
                                            </el-upload>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                        </el-form>
                    </span>
                    <span slot="footer" class="dialog-footer" style="margin-left:290px;">
                        <button class="operatBtn marR5" @click="resetForm('materielForm')">重置</button>
                        <button class="operatBtn marR5" type="primary" @click.stop="onSubmitMaterielForm('materielForm')">保存</button>
                    </span>
                </div>
            </el-col>
        </el-col>
    </el-row>
</template>

<script>
    import http from "@/assets/js/http"
    import _g from "@/assets/js/global"
    // import { getPageData} from "@/assets/js/common.js"
    import { mapGetters } from 'vuex'


    export default {
        data() {
            /* 验证输入是否数字或两位小数 */
            var checkIsNumber = (rule, value, callback) => {
                if (value.length < 1){
                    callback();
                }else{
                    var numReg = /^(((([^0][0-9]*)|0)\.([0-9]{1,2}))|([^0][0-9]*))$/;
                    var numRe = new RegExp(numReg)
                    if (!numRe.test(value)){
                        callback(new Error('请输入整数或两位小数'));
                    }else {
                        callback();
                    }
                }
            };
            return{
                /* --------------------------------------- 物料类别 -------------------------------------------- */
                typeData: [],       //类别数据tree
                rules: {
                    typeId: [
                        { required: true, message: '请选择产品类别', trigger: 'blur' }
                    ],
                    materielName: [
                        { required: true, message: '请输入产品名称', trigger: 'blur' },
                    ],
                    spec: [
                        { required: true, message: '请输入规格型号', trigger: 'blur' },
                    ],
                    price: [
                        { validator:checkIsNumber, trigger: 'blur' },
                    ],
                },

                /* --------------------------------------- 物料 -------------------------------------------- */
                materielForm:{
                    id: '',                 //主键id
                    typeId: '',             //类别id
                    materielName: '',       //物料名称
                    no: '',                 //物料编号
                    spec: '',               //物料规格型号
                    state: '',              //物料状态
                    price: '',              //物料价格
                    remarks: '',            //物料备注
                },
                addFieldForm: {},           //物料新增的字段表
                addField: {},               //物料新增的字段信息列表
                formTitle: '新增物料',      //右边标题
                formConfirmInfo: '',        //右边确认键名称
                imageList: [],              //图片列表
                fileList: [],               //文件列表
                delImageList:[],            //要删除的图片
                delFileList:[],             //要删除的文件
                allowImage: {
                    type: 'image/gif,image/jpeg,image/png,image/jpg',
                    size: 500,  //单位kb
                },
                allowFile: {
                    size: 2048,  //单位kb
                },
            }
        },
        methods: {
            /* --------------------------------------- 物料 -------------------------------------------- */
            /* 重置表单 */
            resetForm: function(formName){
                this.clearMaterielForm(formName);
                let params = this.$route.query;
                if (params.id) {
                    this.getMateriel(params.id);
                }
            },
            /* 清空materielForm */
            clearMaterielForm:function(formName){
                this.$refs[formName].resetFields();
                this.materielForm.id = '';
                this.materielForm.typeId = [];
                this.materielForm.materielName = '';
                this.materielForm.no = '';
                this.materielForm.spec = '';
                this.materielForm.state = '';
                this.materielForm.price = '';
                this.materielForm.remarks = '';
                this.imageList = [];
                this.fileList = [];
                this.delImageList = [];
                this.delFileList = [];
            },
            /* 根据id获取物料信息 */
            getMateriel:function(id){
                this.apiPost('materiel/read',{id:id}).then(res=>{
                    if (res.code != 200){
                        _g.toastMsg("error", res.message);
                    }else{
                        let data = res.data;
                        let pId = [];
                        this.formTitle = '物料修改';
                        this.formConfirmInfo = '修改'+data.materiel_name;
                        if (data.type.path.length > 1){
                            let path = data.type.path.substr(1,data.type.path.length-2);
                            let key = 0;
                            path = path.split('-');
                            for (let value of path) {
                                pId[key] = Number(value);
                                key++;
                            }
                        }
                        pId.push(res.data.type.id);
                        this.materielForm.typeId = pId;
                        this.materielForm.id = data.id;
                        this.materielForm.materielName = data.materiel_name;
                        this.materielForm.no = data.materiel_no == null ? '' : data.materiel_no;
                        this.materielForm.spec = data.materiel_spec;
                        this.materielForm.state = data.materiel_state;
                        this.materielForm.price = data.materiel_price;
                        this.materielForm.remarks = data.materiel_remarks;

                        for (let i in this.addField){
                            let key = this.addField[i]['field_name'];
                            this.addFieldForm[key] = data[key] ? data[key] : '';
                        }
                        if (data.images.length > 0){
                            for (let i in data.images){
                                this.imageList.push({name:data.images[i].img_name,url:data.images[i].image_url,id:data.images[i].id});
                            }
                        }
                        if (data.files.length > 0){
                            for (let i in data.files){
                                this.fileList.push({name:data.files[i].old_name,url:data.files[i].file_url,id:data.files[i].id});
                            }
                        }
                    }
                });
            },
            /* 提交物料表单到后台，新建和修改 */
            onSubmitMaterielForm:function(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$confirm('是否确认 '+this.formConfirmInfo+' ?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                            center: true
                        }).then(()=>{
                           // _g.showLoading('提交中');
                            var formData = new FormData();
                            for (let x in this.materielForm){
                                if (x == 'typeId'){
                                    formData.append(x,this.materielForm[x][this.materielForm[x].length-1]);
                                }else{
                                    formData.append(x,this.materielForm[x]);
                                }
                            }
                            for (let i in this.addFieldForm){
                                if ((i != '[object Object]')){
                                    formData.append('addField-'+i,this.addFieldForm[i]);
                                }
                            }
                            if (this.delImageList.length > 0){
                                for (let m in this.delImageList){
                                    formData.append('delImage[]',this.delImageList[m]);
                                }
                            }
                            if (this.delFileList.length > 0){
                                for (let n in this.delFileList){
                                    formData.append('delFile[]',this.delFileList[n]);
                                }
                            }
                            for(let i=0;i<this.imageList.length;i++){
                                if (this.imageList[i].raw){
                                    formData.append('image[]',this.imageList[i].raw);
                                }
                            }
                            for(let j=0;j<this.fileList.length;j++){
                                if (this.fileList[j].raw){
                                    formData.append('file[]',this.fileList[j].raw);
                                }
                            }
                            this.apiPost('/materiel/save',formData).then(data=>{
                                _g.showLoading().close();
                                if(typeof data === 'string'){
                                    data = JSON.parse(data);
                                }
                                if (data.code != 200){
                                    _g.toastMsg("error", data.message);
                                    return;
                                }
                                this.clearMaterielForm('materielForm');
                                for (let i in this.addField){
                                    let key = this.addField[i]['field_name'];
                                    this.addFieldForm[key] = '';
                                }
                                _g.toastMsg("success", data.message);
                                /*setTimeout( function(){    //自动关闭当前窗口
                                    window.opener=null;
                                    window.close();
                                }, 1500 );*/
                            });
                        }).catch(()=>{
                            _g.toastMsg("error", data.message);
                        });
                    } else {
                        return false;
                    }
                });
            },
            //图片状态改变时
            onImageChange(file,fileList){
                this.imageList = fileList;
                console.log(file,fileList);
                //this.exceed(file,fileList);
            },
            //文件状态改变时
            onFileChange(file,fileList){
                this.fileList = fileList;
            },
            //文件列表移除文件时
            onFileRemove(file,fileList){
                this.delFileList.push(file.id);
                this.fileList = fileList;
            },
            //图片列表移除图片时
            onImageRemove(file,fileList){
                this.delImageList.push(file.id);
                this.imageList = fileList;
            },
            /* 上传前验证文件 */
            beforeUploadFile: function(file) {
                if (this.checkFileSize(file.size,this.allowFile.size)){
                    return true;
                }else{
                    return false;
                }
            },
            /* 上传前验证图片 */
            beforeUploadImage: function(file) {
                if (this.checkFileType(file.type,this.allowImage.type) && this.checkFileSize(file.size,this.allowImage.size)){
                    return true;
                }else{
                    return false;
                }
            },
            /* 验证文件类型 */
            checkFileType: function(type,allowType) {
                if (type !='' && allowType.indexOf(type) >= 0){
                    return true;
                }else{
                    _g.toastMsg("error", '文件类型错误，只允许'+allowType);
                    return false;
                }
            },
            /* 验证文件大小 */
            checkFileSize: function(size,allowSize) {
                if (allowSize*1024 >= size){
                    return true;
                }else{
                    _g.toastMsg("error", '文件太大,最大允许'+allowSize+'kb');
                    return false;
                }
            },
            /* 验证文件个数 */
            exceed: function(files,fileList){
                console.log(files,fileList);
                if (files.length > 5){
                    _g.toastMsg("error", '最多5张图片');
                }
            },
            /* 修改物料时显示原有的图片 */
            getImages:function (images) {
                let imageArr = [];
                for (let i in images){
                    imageArr.push(images[i].image_url);
                }
                return imageArr;
            },
            /* 修改物料时显示原有的文件 */
            getFiles:function (files) {
                let fileArr = [];
                for (let i in files){
                    fileArr.push({name:files[i].old_name,url:files[i].file_url});
                }
                return fileArr;
            },
            /* --------------------------------------- 物料类别 -------------------------------------------- */
            /* 单击类别事件 */
            nodeClick: function(data) {
                if (data.children){
                    return;
                }
                let pId = [];
                if (data.path.length > 1){
                    let path = data.path.substr(1,data.path.length-2);
                    let key = 0;
                    path = path.split('-');
                    for (let value of path) {
                        pId[key] = Number(value);
                        key++;
                    }
                }
                pId.push(data.id);
                this.materielForm.typeId = pId;
            },
            //获取物料类别
            getTypeList: function () {
                this.apiPost('/materiel/type/all','').then(res=>{
                    this.typeData = res.data;
                });
            },
            /* 获取物料字段 */
            getMaterielField:function () {
                this.apiPost('materiel/field/get','').then(res=>{
                    if (res){
                        this.addField = res;
                        for (let i in this.addField){
                            let key = this.addField[i]['field_name'];
                            Vue.set(this.addFieldForm,key,'');
                        }
                    }
                });
            },
        },
        mounted: function () {
            this.getMaterielField();
            this.getTypeList();
            let params = this.$route.query;
            if (params.id){
                this.getMateriel(params.id);
            }else{
                this.formTitle = '新建物料';
                this.formConfirmInfo = '新建';
            }
        },
        mixins: [http]
    }
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
    $color-blue: #2196F3;
    $space-width: 18px;
    .ms-tree-space {
        position: relative;
        top: 1px;
        display: inline-block;
        font-style: normal;
        font-weight: 400;
        line-height: 1;
        width: $space-width;
        height: 14px;
        &::before {
            content: ""
        }
    }
    .left-sider{
        height: 100%;
        overflow: hidden;
    }
    .right-content {
        height: 100%;
    }
    .custom-tree-node {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 12px;
        padding-right: 20px;
    }
    .split-line{
        width: 2px;
        border-left: 1px solid #d1d1d1;
        border-right: 1px solid #d1d1d1;
        background-color: #E6EEF8;
        height: 100%;
        cursor:w-resize;
        float: left;
    }
</style>